<template>
    <div class="com-container">
        <div class="com-chart" id="com-chart" ref="seller_ref"></div>
    </div>
</template>

<script setup>
import {
    inject,
    onMounted,
    onUnmounted,
    defineExpose,
    ref,
    computed,
    watch,
} from "vue";
import useChartTest from "@/hooks/useChart";
//vuex
import { useStore } from "vuex";
const store = useStore();
import SocketService from "./../utils/socket_service";
import * as echarts from "echarts";

const useChart = () => {
    let currentPage = 1;
    let totalPage = null;
    let allData = null;
    let chartInstance = null;
    let timer = null;
    const seller_ref = ref(null);
    //初始化chart对象
    const initChart = () => {
        chartInstance = echarts.init(
            document.querySelector("#com-chart"),
            theme.value
        );
        const initOption = {
            title: {
                text: "| 商家销售统计",
                textStyle: {},
                left: 20,
                top: 20,
            },
            grid: {
                top: "20%",
                left: "10%",
                bottom: "10%",
                right: "10%",
                constainLable: true,
            },
            xAxis: {
                type: "value",
            },
            yAxis: {
                type: "category",
            },
            tooltip: {
                show: true,
                tigger: "axis",
                axisPointer: {
                    type: "line",
                    z: 0,
                    lineStyle: {
                        color: "#f1f1f1",
                        type: "solid",
                        width: 80,
                    },
                },
            },
            series: [
                {
                    type: "bar",
                    label: {
                        position: "right",
                        show: true,
                    },
                    itemStyle: {
                        color: {
                            type: "linear ", // linear 线性渐变  radial径向渐变
                            x: 0,
                            y: 0,
                            x2: 1,
                            y2: 0,
                            colorStops: [
                                {
                                    offset: 0,
                                    color: "#5052EE", // 0% 处的颜色
                                },
                                {
                                    offset: 1,
                                    color: "#AB6EE5", // 100% 处的颜色
                                },
                            ],
                            global: false, // 缺省为 false
                        },
                    },
                },
            ],
        };
        chartInstance.setOption(initOption);
        chartInstance.on("mouseover", () => {
            clearInterval(timer);
        });
        chartInstance.on("mouseout", () => {
            startIntarval();
        });
    };
    //获取数据
    const getData = async (ret) => {
        // const { data: ret } = await inject("http").get("/api/seller");
        console.log(ret);
        allData = ret;
        //对数组排序
        allData.sort((a, b) => a.value - b.value);
        totalPage =
            allData.length % 5 === 0
                ? allData.length / 5
                : allData.length / 5 + 1;
        updatedChart();
        startIntarval();
    };
    //更新图表
    const updatedChart = () => {
        const start = (currentPage - 1) * 5;
        const end = currentPage * 5;
        const showData = allData.slice(start, end);
        console.log(showData);
        const sellerNames = showData.map((item) => {
            return item.name;
        });
        const sellerValues = showData.map((item) => {
            return item.value;
        });
        const dataOption = {
            yAxis: {
                data: sellerNames,
            },

            series: [
                {
                    data: sellerValues,
                },
            ],
        };
        chartInstance.setOption(dataOption);
    };

    //自动翻页
    const startIntarval = () => {
        if (timer) {
            clearInterval(timer);
        }
        timer = setInterval(() => {
            currentPage++;
            if (currentPage > totalPage) {
                currentPage = 1;
            }
            updatedChart();
        }, 3000);
    };

    onUnmounted(() => {
        clearInterval(timer);
        window.removeEventListener("resize", screenAdapt);
    });

    //响应式适配
    const screenAdapt = () => {
        const com_chart = document.querySelector("#com-chart");
        console.log(com_chart.offsetWidth);
        const titleFontSize = com_chart.offsetWidth * (66 / 1536);
        console.log("--------------", titleFontSize);
        const adaptOption = {
            title: {
                textStyle: {
                    fontSize: titleFontSize,
                },
            },
            series: [
                {
                    barWidth: titleFontSize,
                    itemStyle: {
                        borderRadius: [
                            0,
                            titleFontSize / 2,
                            titleFontSize / 2,
                            0,
                        ],
                    },
                },
            ],
        };
        chartInstance.setOption(adaptOption);
        chartInstance.resize();
    };

    // 回调函数注册
    inject("SocketService").registerCallBack("sellerData", getData);
    onUnmounted(() => {
        inject("SocketService"), unRegisterCallBack("sellerData");
    });

    onMounted(() => {
        initChart();
        // getData();
        // getData();
        SocketService.Instance.send({
            action: "getData",
            socketType: "sellerData",
            chartName: "seller",
            value: "",
        });
        window.addEventListener("resize", screenAdapt);
        screenAdapt();
    });

    //更换主题
    const theme = computed(() => {
        return store.state.theme;
    });
    watch(theme, () => {
        console.log("主题切换了");
        chartInstance.dispose(); //销毁当前图表
        initChart();
        SocketService.Instance.send({
            action: "getData",
            socketType: "sellerData",
            chartName: "seller",
            value: "",
        });
        console.log(theme.value);
    });

    return {
        screenAdapt,
    };
};

const { screenAdapt } = useChart();

defineExpose({
    screenAdapt,
});
</script>

<style lang="scss">
#test {
    width: 500px;
    height: 500px;
}
</style>
